package org.springframework.prospring.ticket.dao.hibernate;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.prospring.ticket.dao.CityDAO;
import org.springframework.prospring.ticket.domain.location.City;
import org.springframework.prospring.ticket.domain.location.Region;
import org.springframework.prospring.ticket.exception.BusinessException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.lang.StringUtils;

import java.util.Collection;

/**
 * This class interacts with Spring and Hibernate to save and
 * retrieve User objects.
 *
 * @author Alexis Quiros
 */
public class CityDAOHibernate extends HibernateDaoSupport implements CityDAO {
    private static Log log = LogFactory.getLog(CityDAOHibernate.class);

    public CityDAOHibernate() {
        super();
        if (log.isDebugEnabled()) {
            log.debug("in CityDAOHibernate Constructor");
        }
    }

    public City findCity(Long cityId) {
        if (log.isDebugEnabled()) {
            log.debug("finding City id: " + cityId);
        }

        City city = (City)getHibernateTemplate().load(City.class, cityId);

        return city;
    }


    public Collection<City> findAllCities() {
        if (log.isDebugEnabled()) {
            log.debug("finding all Cities ");
        }

        Collection<City> cities = getHibernateTemplate().find("from City");
        return cities;
    }

    public Collection <Region> findRegionsByCity(Long cityId){
        if (log.isDebugEnabled()) {
            log.debug("Finding Regions for City id: " + cityId);
        }

        City city = this.findCity(cityId);
        Collection<Region> regions = city.getRegions();
        return regions;
    }


    public void saveCity(City city) throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("Saving City: " + city);
        }

        if (StringUtils.isEmpty(city.getName())) {
            String message = "The name is required, name="+city.getName();
            log.info(message);
            throw new BusinessException(message);
        }

        getHibernateTemplate().saveOrUpdate(city);

        if (log.isDebugEnabled()) {
            log.debug("cityId set to: " + city.getId());
        }
    }

    public void removeCity(Long cityId) {
        if (log.isDebugEnabled()) {
            log.debug("removing City id: " + cityId);
        }

        Object city = getHibernateTemplate().load(City.class, cityId);
        getHibernateTemplate().delete(city);
    }


}
